﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.Com;
using System.Net;
using System.Globalization;
using Reader.BLE.Models;
using System.IO;

namespace Reader.BLE.UserControls
{
    public partial class ReaderItem : UserControl
    {
        static AsyncTcpServer server;
        static string IP = "";
        static int Port = 0;
        static string API = "";
        static RichTextBoxLog _log = null;
        static List<Device> Devices = null;
        static List<Employee> Employees = null;
        public ReaderItem()
        {
            InitializeComponent();
        }
        public ReaderItem(string ip, int port, string url, RichTextBox rtx)
        {
            InitializeComponent();
            IP = ip;
            Port = port; API = url;
            _log = new RichTextBoxLog(rtx);
            Devices = GetDevices();
            Employees = GetEmployes();
            this.lblText.Text = $"TCP/IP:{ip}:{port}";
        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                Start(IP, Port);

            }
            catch (Exception ex)
            {
                _log.LogMessage($"启动服务失败:{ex.Message}");
            }

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (server != null && server.IsRunning)
                {
                    server.Stop();
                    server.Dispose();
                    btnStop.Enabled = false;
                    btnStart.Enabled = true;

                    _log.LogMessage($"{IP}:{Port}监听已停止.");
                }

            }
            catch (Exception ex)
            {
                _log.LogMessage($"停止服务失败:{ex.Message}");
            }

        }

        private void ReaderItem_Load(object sender, EventArgs e)
        {

        }

        void Start(string ip, int port)
        {
            //server = new AsyncTcpServer(IPAddress.Parse("192.168.31.103"), 9999);

            server = new AsyncTcpServer(IPAddress.Parse(ip), port);
            server.Encoding = Encoding.UTF8;
            server.ClientConnected +=
              new EventHandler<TcpClientConnectedEventArgs>(server_ClientConnected);
            server.ClientDisconnected +=
              new EventHandler<TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            server.PlaintextReceived +=
              new EventHandler<TcpDatagramReceivedEventArgs<string>>(server_PlaintextReceived);
            if (!server.IsRunning)
            {
                server.Start();
                //$"{ip}:TCP server has been started.".Log();
                _log.LogMessage($"{ip}:{port}监听已启动.");
                btnStop.Enabled = true;
                btnStart.Enabled = false;
            }


            //"Type something to send to client...".Log();

            //while (IsRunning)
            //{
            //    string text = Console.ReadLine();
            //    server.SendAll(text);
            //}
        }

        static void server_ClientConnected(object sender, TcpClientConnectedEventArgs e)
        {
            //(string.Format(CultureInfo.InvariantCulture,
            //  "TCP client {0} has connected.",
            //  e.TcpClient.Client.RemoteEndPoint.ToString())).Log();

            _log.LogMessage(string.Format(CultureInfo.InvariantCulture,
              "TCP client {0} has connected.",
              e.TcpClient.Client.RemoteEndPoint.ToString()));
        }

        static void server_ClientDisconnected(object sender, TcpClientDisconnectedEventArgs e)
        {
            _log.LogMessage(string.Format(CultureInfo.InvariantCulture,
              "TCP client {0} has disconnected.",
              e.TcpClient.Client.RemoteEndPoint.ToString()));
        }

        static void server_PlaintextReceived(object sender, TcpDatagramReceivedEventArgs<string> e)
        {
            string clientIp = ((System.Net.IPEndPoint)e.TcpClient.Client.RemoteEndPoint).Address.ToString();
            var device = Devices.Where(p => p.IP == clientIp.Trim()).FirstOrDefault();
            string position = "未设置位置信息";
            if (device != null && device.Position.IsNotNull())
                position = device.Position;
            //string  res = "D776A8FEB78E,0,\"Jinou_Beacon\",4,0D094A696E6F755F426561636F6E,-48";
            string res = e.Datagram.Replace("\r\n", "").Replace("+INQRESULT:", "");
            // _log.LogWarning(res); 
            string[] fields = res.Split(',');
            if (fields.Length != 6) return;
            // Console.WriteLine(res);
            //res = "D776A8FEB78E,0,\"Jinou_Beacon\",4,0D094A696E6F755F426561636F6E,-48";
            string mac = fields[0];
            _log.LogSuccess($"MAC=={mac}");
            var emp = Employees.Where(p => p.MAC == mac).FirstOrDefault();
            if (emp == null) return;

            string pars = $"EmployeeNo={emp.EmployeeNo}&EmployeeName={emp.EmployeeName}&EmpLocation={position}&DateTime={DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}&DeviceAddr={fields[0]}&DeviceAddrType={fields[1]}&DeviceName={fields[2].Replace("\"", "")}&DeviceRssi={fields[5]}";
            var xml = HttpHelper.POST(API, pars);
            xml = xml.Replace("xmlns=\"http://tempuri.org/\"", "");
            var httpres = XmlHelper.XmlDeserialize<string>(xml);
            _log.LogSuccess($"Upload==>EmployeeNo={emp.EmployeeNo}&EmployeeName={emp.EmployeeName}&EmpLocation={position}:{httpres}");
        }

        private List<Device> GetDevices()
        {
            //读取配置
            try
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Iots", "Device.json");
                if (!File.Exists(path))
                {
                    _log.LogMessage("Device.json文件不存在!");
                    return null;
                }
                else
                {
                    //读取json文件
                    string json = "";
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                    {
                        json = sr.ReadToEnd();
                    }
                    var devices = json.FromJson<List<Device>>();
                    return devices;

                }
            }
            catch (Exception ex)
            {
                _log.LogError($"InitConfig.Error={ex.Message}");
                return null;
            }

        }
        private List<Employee> GetEmployes()
        {
            //读取配置
            try
            {
                var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Iots", "Employee.json");
                if (!File.Exists(path))
                {
                    _log.LogMessage("Device.json文件不存在!");
                    return null;
                }
                else
                {
                    //读取json文件
                    string json = "";
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                    {
                        json = sr.ReadToEnd();
                    }
                    var employees = json.FromJson<List<Employee>>();
                    return employees;

                }
            }
            catch (Exception ex)
            {
                _log.LogError($"InitConfig.Error={ex.Message}");
                return null;
            }

        }

    }
}
